package lyxs_916.http_utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


/**
 * 类说明:访问网络的线程,下载一个图片
 * Created by 阳 on 2016/9/29
 */

public class HttpUtilImageView extends Thread {
    private String url;
    private Handler handler;
    private ImageView imageView;

    FileOutputStream out = null;
    InputStream in;

    public HttpUtilImageView(String url, Handler handler, ImageView imageView) {
        this.url = url;
        this.handler = handler;
        this.imageView = imageView;
    }

    @Override
    public void run() {
        try {
            //1，把字符串转换成url
            URL httpUrl = new URL(url);
            //2，通过url获取网络连接对象
            HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            httpURLConnection.setReadTimeout(5000);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setDoInput(true);//设置可以获取一个输入流
            in = httpURLConnection.getInputStream();


            File downloadFile = null;
            String fileName = String.valueOf(System.currentTimeMillis());
            //判断否是有储存卡
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                File filePath = Environment.getExternalStorageDirectory();
                downloadFile = new File(filePath, fileName+".jpg");
                out = new FileOutputStream(downloadFile);
            }

            byte[] bytes = new byte[2048];
            int length;
            if (out != null) {
                while ((length = in.read(bytes)) != -1) {
                    out.write(bytes, 0, length);
                }
            }

            final Bitmap bitmap = BitmapFactory.decodeFile(downloadFile.getPath());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setImageBitmap(bitmap);
                }
            });

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.run();
    }
}
